﻿Imports System.Globalization

Partial Public Class frm_MyBooking
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Dim clsFc As New ClassFunction
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "MY BOOKING"
            If (Session("Role") & "" = "00002") Then
                gridBooking.Columns(0).Visible = True
                gridBooking.Columns(1).Visible = False
            Else
                gridBooking.Columns(0).Visible = False
                gridBooking.Columns(1).Visible = True
            End If
            LoadDataMyBooking("", "", "", "")
        End If
    End Sub

    Private Sub LoadDataMyBooking(ByVal booking As String, ByVal vessel As String, ByVal Datefrom As String, ByVal Dateto As String)
        panelMain.Visible = True
        PanelAdd.Visible = False
        PanelSub.Visible = False
        Dim dt As DataTable
        If (Session("Role") & "" = "00002") Or (Session("Role") & "" = "00007") Then
            dt = clsGet.Get_PreBooking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "", booking, vessel, Datefrom, Dateto, CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), "'CV','CC','CM','CR','CA'")
        Else
            dt = clsGet.Get_PreBooking("", booking, vessel, Datefrom, Dateto, "", "'CV','CC','CM','CR','CA'")
        End If

        ViewState("MyBooking") = dt
        gridBooking.DataSource = dt
        gridBooking.DataBind()
    End Sub

    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim CurrentIndex As Integer = gridBooking.PageIndex
        Select Case e.CommandArgument.ToString().ToLower()
            Case "first"
                gridBooking.PageIndex = 0
            Case "prev"
                If (gridBooking.PageIndex <> 0) Then
                    gridBooking.PageIndex = CurrentIndex - 1
                End If
            Case "next"
                If (gridBooking.PageIndex <> gridBooking.PageCount) Then
                    gridBooking.PageIndex = CurrentIndex + 1
                End If
            Case "last"
                gridBooking.PageIndex = gridBooking.PageCount
        End Select
        gridBooking.DataSource = ViewState("MyBooking")
        gridBooking.DataBind()
    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim Page As GridViewRow = gridBooking.BottomPagerRow
        Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
        gridBooking.PageIndex = ddlPage.SelectedIndex
        gridBooking.DataSource = ViewState("MyBooking")
        gridBooking.DataBind()
    End Sub

    Public Function CreateDatatable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Booking_no", GetType(String))
        dt.Columns.Add("Vehicle_Text", GetType(String))
        dt.Columns.Add("Date_From", GetType(String))
        dt.Columns.Add("Date_To", GetType(String))
        dt.Columns.Add("Status", GetType(String))
        dt.Columns.Add("MAgent_no", GetType(String))
        dt.Columns.Add("PORT", GetType(String))
        dt.Columns.Add("MAgent_name", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub gridBooking_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridBooking.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridBooking.PageIndex <> 0) Then
            Index = Index Mod (gridBooking.PageIndex * 10)
        End If
        Dim dt As DataTable = CreateDatatable()
        Dim dr As DataRow = dt.NewRow
        dr.Item("Booking_no") = gridBooking.DataKeys(Index).Values("Booking_no")
        dr.Item("Vehicle_Text") = gridBooking.DataKeys(Index).Values("Vehicle_Text")
        dr.Item("Date_From") = gridBooking.DataKeys(Index).Values("Date_From")
        dr.Item("Date_To") = gridBooking.DataKeys(Index).Values("Date_To")
        dr.Item("Status") = gridBooking.DataKeys(Index).Values("Status")
        dr.Item("MAgent_no") = gridBooking.DataKeys(Index).Values("MAgent_no")
        dr.Item("MAgent_name") = gridBooking.DataKeys(Index).Values("MAgent_name")
        dr.Item("PORT") = gridBooking.DataKeys(Index).Values("PORT")
        dt.Rows.Add(dr)
        dt.AcceptChanges()
        gridsub.DataSource = dt
        gridsub.DataBind()

        ViewState("Booking") = gridBooking.DataKeys(Index).Values("Booking_no") & ""
        If e.CommandName = "Booking" Then
            Dim _Date As String = ""
            If (gridBooking.DataKeys(Index).Values("Date_From") & "" <> "") Then
                If (gridBooking.DataKeys(Index).Values("Date_From") & "" = gridBooking.DataKeys(Index).Values("Date_To") & "") Then
                    _Date = gridBooking.DataKeys(Index).Values("Date_To")
                Else
                    _Date = gridBooking.DataKeys(Index).Values("Date_From").ToString.Substring(0, 2) & "-" & gridBooking.DataKeys(Index).Values("Date_To")
                End If
            End If
            panelMain.Visible = False
            PanelSub.Visible = True
            panelBooking.Visible = True
            panelEstimate.Visible = False
            Dim dtwharf As DataTable = clsGet.Get_BookingWharf_ForMYBooking(gridBooking.DataKeys(Index).Values("Booking_no") & "")
            Dim Wharf As String = ""
            Dim Plan As String = ""
            Dim Depart As String = ""
            If (dtwharf.Rows.Count = 1) Then
                Wharf = dtwharf.Rows(0).Item("Wharf") & ""
                Plan = dtwharf.Rows(0).Item("Date_From") & " - " & dtwharf.Rows(0).Item("TimeStart")
                Depart = dtwharf.Rows(0).Item("Date_To") & " - " & dtwharf.Rows(0).Item("TimeEnd")
            End If
            GenBOoking(gridBooking.DataKeys(Index).Values("Booking_no") & "", gridBooking.DataKeys(Index).Values("MAgent_no") & " - " & gridBooking.DataKeys(Index).Values("MAgent_name"), _Date, gridBooking.DataKeys(Index).Values("Vehicle_Text") & "", Wharf, Plan, Depart)
        ElseIf (e.CommandName = "Estimate") Then
            panelMain.Visible = False
            PanelSub.Visible = True
            panelBooking.Visible = False
            panelEstimate.Visible = True
            LiEstimate.Text = GetActual(gridBooking.DataKeys(Index).Values("Booking_no") & "", gridBooking.DataKeys(Index).Values("PORT") & "", gridBooking.DataKeys(Index).Values("MAgent_no") & "")
        ElseIf (e.CommandName = "Payment") Then

        ElseIf (e.CommandName = "AddData") Then
            ViewState("PreBooking") = gridBooking.DataKeys(Index).Values("Booking_no") & ""
            BindDataEditPre(gridBooking.DataKeys(Index).Values("Booking_no") & "")
            PanelAdd.Visible = True
            panelMain.Visible = False
        End If
    End Sub

    Private Sub BindDataEditPre(ByVal Booking As String)
        Dim dt As DataTable = clsGet.Get_PreBookingOneRecord(Booking)
        If (dt.Rows.Count = 0) Then
            dt = clsGet.Get_BookingOneRecord(Booking).Tables(0)
        End If
        If (dt.Rows(0).Item("status") & "" <> "N") Then
            btnSaveBooking.Visible = False
            btnSave.Visible = False
        Else
            btnSaveBooking.Visible = True
            btnSave.Visible = True
        End If

        Session("Product_popup") = clsGet.Get_Booking_Product(Booking)
        gridProductShow.DataSource = Session("Product_popup")
        gridProductShow.DataBind()

        Session("Q88") = clsGet.Get_BookingUpload(Booking)
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()

        txtid.Text = dt.Rows(0).Item("MAgent_no") & "-" & dt.Rows(0).Item("MAgent_name")
        txtAgent.Text = dt.Rows(0).Item("SAgent_no") & "-" & dt.Rows(0).Item("SAgent_name")
        If (txtid.Text.Trim() = "-") Then
            txtid.Text = String.Empty
        End If
        If (txtAgent.Text.Trim() = "-") Then
            txtAgent.Text = String.Empty
        End If
        If (dt.Rows(0).Item("Vehicle_no") & "" <> "999999999") And (dt.Rows(0).Item("Vehicle_no") & "" <> "") Then
            PanelVEHICLE_OUT.Visible = False
            PanelVEHICLE_IN.Visible = True
            PanelVEHICLE_IN_DETAIL.Visible = True
            txtVessel.Text = dt.Rows(0).Item("Vehicle_no") & "-" & dt.Rows(0).Item("Vehicle_Text")
            lbLOASHOW.Text = dt.Rows(0).Item("Vehicle_LOA") & ""
            lbDraft.Text = dt.Rows(0).Item("Vehicle_Draft") & ""
            lbDWTSHow.Text = dt.Rows(0).Item("Vehicle_DWT") & ""
            lbGRTSHow.Text = dt.Rows(0).Item("Vehicle_GRT") & ""
            lbNation.Text = dt.Rows(0).Item("Vehicle_CNTRY") & ""
        Else
            txtVesselOUT.Text = dt.Rows(0).Item("Vehicle_Text") & ""
            txtLOA.Text = dt.Rows(0).Item("Vehicle_LOA") & ""
            txtDraft.Text = dt.Rows(0).Item("Vehicle_Draft") & ""
            txtDWT.Text = dt.Rows(0).Item("Vehicle_DWT") & ""
            txtGRT.Text = dt.Rows(0).Item("Vehicle_GRT") & ""
            If Not (ddlNation.Items.FindByValue(dt.Rows(0).Item("Vehicle_CNTRY") & "") Is Nothing) Then
                ddlNation.SelectedValue = dt.Rows(0).Item("Vehicle_CNTRY")
            End If
            PanelVEHICLE_OUT.Visible = True
            PanelVEHICLE_IN.Visible = False
            PanelVEHICLE_IN_DETAIL.Visible = False
        End If
        txtDate.Text = dt.Rows(0).Item("Date_From") & ""
        txtDateTo.Text = dt.Rows(0).Item("Date_To") & ""
        txtDateBooking.Text = dt.Rows(0).Item("Booking_Date") & ""
        txtTimeBooking.Text = dt.Rows(0).Item("Booking_Time") & ""

        If ((dt.Rows(0).Item("Lay_Time") & "" <> "0") And (dt.Rows(0).Item("Lay_Time") & "" <> "")) Or ((dt.Rows(0).Item("Demurrage") & "" = "0") And (dt.Rows(0).Item("Demurrage") & "" = "")) Then
            radioDemurrage.ClearSelection()
            radioDemurrage.SelectedValue = "Y"
            rowLaytime.Visible = True
            txtLayTime.Text = dt.Rows(0).Item("Lay_Time")
            txtDemurrage.Text = dt.Rows(0).Item("Demurrage")
            If Not (ddlDemurrage.Items.FindByValue(dt.Rows(0).Item("Demurrage_Money") & "") Is Nothing) Then
                ddlDemurrage.SelectedValue = dt.Rows(0).Item("Demurrage_Money") & ""
            End If
        Else
            txtLayTime.Text = "0"
            txtDemurrage.Text = "0"
            radioDemurrage.ClearSelection()
            radioDemurrage.SelectedValue = "N"
            rowLaytime.Visible = False
        End If

        txtWater.Text = dt.Rows(0).Item("Water_Point")
        If (dt.Rows(0).Item("BunkerFO_chk") & "" = "Y") Then
            chkFO.Checked = True
            txtFO.Text = dt.Rows(0).Item("BunkerFO_Point") & ""
        Else
            txtFO.Text = "0"
        End If
        If (dt.Rows(0).Item("BunkerDO_chk") & "" = "Y") Then
            chkDO.Checked = True
            txtDO.Text = dt.Rows(0).Item("BunkerDO_Point") & ""
        Else
            txtDO.Text = "0"
        End If

        If Not (raioType.Items.FindByValue(dt.Rows(0).Item("Vehicle_Destination")) Is Nothing) Then
            raioType.SelectedValue = dt.Rows(0).Item("Vehicle_Destination")
            If (radioTypeBuy.SelectedValue = "O") Then
                rowTypeBuy.Visible = True
                If Not (radioTypeBuy.Items.FindByValue(dt.Rows(0).Item("Vehicle_TypeBuy")) Is Nothing) Then
                    radioTypeBuy.SelectedValue = dt.Rows(0).Item("Vehicle_TypeBuy")
                End If
            End If
        End If
        If Not (radioPort.Items.FindByValue(dt.Rows(0).Item("PORT")) Is Nothing) Then
            radioPort.SelectedValue = dt.Rows(0).Item("PORT")
        End If
        txtRemark.Text = dt.Rows(0).Item("Remark")
    End Sub

    Private Sub FormatN(ByRef data As String)
        Try
            data = FormatNumber(data, 2)
        Catch ex As Exception

        End Try
    End Sub
    Private Sub gridBooking_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridBooking.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim imgBooking As ImageButton = CType(e.Row.FindControl("imgBooking"), ImageButton)
            Dim imgEstimate As ImageButton = CType(e.Row.FindControl("imgEstimate"), ImageButton)
            Dim imgPayment As ImageButton = CType(e.Row.FindControl("imgPayment"), ImageButton)
            Dim dt As DataTable
            If (gridBooking.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                dt = clsGet.GetTemp_Estimate(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", "")
            Else
                If (Session("Role") & "" = "00002") Then
                    dt = clsGet.GetTemp_Estimate(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no"))
                Else
                    dt = clsGet.GetTemp_Estimate(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", "")
                End If
            End If
            If (dt.Rows.Count > 0) Then
                imgEstimate.ImageUrl = "../Image/Correct.png"
            Else
                Dim dtbooking As DataTable = clsGet.Get_BookingOneRecord(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "").Tables(0)
                If (dtbooking.Rows.Count > 0) Then
                    If (dtbooking.Rows(0).Item("Marketing_approve") & "" = "") Then
                        imgEstimate.ImageUrl = "../Image/NotCorrect.png"
                    Else
                        imgEstimate.ImageUrl = "../Image/Correct.png"
                    End If
                Else
                    imgEstimate.ImageUrl = "../Image/NotCorrect.png"
                End If
            End If

            If (gridBooking.DataKeys(e.Row.RowIndex).Values("Date_From") & "" <> "") Then
                If (gridBooking.DataKeys(e.Row.RowIndex).Values("Date_From") & "" = gridBooking.DataKeys(e.Row.RowIndex).Values("Date_To") & "") Then
                    e.Row.Cells(3).Text = gridBooking.DataKeys(e.Row.RowIndex).Values("Date_To")
                Else
                    e.Row.Cells(3).Text = gridBooking.DataKeys(e.Row.RowIndex).Values("Date_From").ToString.Substring(0, 2) & "-" & gridBooking.DataKeys(e.Row.RowIndex).Values("Date_To")
                End If
            End If
            If (gridBooking.DataKeys(e.Row.RowIndex).Values("Status") & "" = "N") Then
                imgBooking.ImageUrl = "../Image/NotCorrect.png"
                imgPayment.ImageUrl = "../Image/NotCorrect.png"
            Else
                imgBooking.ImageUrl = "../Image/Correct.png"
                dt = clsGet.Get_BookingOneRecord(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "").Tables(0)
                If (dt.Rows.Count > 0) Then
                    If (dt.Rows(0).Item("Payin") & "" = "0") Then
                        If (Session("Role") & "" = "00002") Then
                            If (clsGet.GetPayinAdvance(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no"))) Then
                                imgPayment.ImageUrl = "../Image/Correct.png"
                            Else
                                imgPayment.ImageUrl = "../Image/NotCorrect.png"
                            End If
                        Else
                            If (clsGet.GetPayinAdvance(gridBooking.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", dt.Rows(0).Item("MAgent_no") & "")) Then
                                imgPayment.ImageUrl = "../Image/Correct.png"
                            Else
                                imgPayment.ImageUrl = "../Image/NotCorrect.png"
                            End If
                        End If
                    ElseIf (dt.Rows(0).Item("Status") & "" = "FN") Then
                        imgPayment.ImageUrl = "../Image/Correct.png"
                    Else
                        imgPayment.ImageUrl = "../Image/NotCorrect.png"
                    End If
                Else
                    imgPayment.ImageUrl = "../Image/NotCorrect.png"
                End If
            End If

        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridBooking.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridBooking.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridBooking.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                    ddlPage.Items(i).Attributes.Add("Style", "height:60px")
                Next

            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridBooking.PageCount.ToString()
            End If
        End If
    End Sub

    Protected Function GetActual(ByVal Booking_no As String, ByVal PORT As String, ByVal MAgent_no As String) As String
        HeadReport(Booking_no)

        Dim HTML As String = ""
        HTML = "<table width='95%'  style='border-width: 0px;' border='1' cellpadding='0' cellspacing='0'>"
        HTML &= "<tr style='background-color:#32cd32;'>"
        HTML &= "<td style='width:140px;' valign='top'  align='center'><font class='White-Style-Head' style='color:#000000'>Code</font>&nbsp;</td>"
        HTML &= "<td style='width:280px;' align='center'><font class='White-Style-Head' style='color:#000000'>DESCRIPTION</font></td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='center'><font class='White-Style-Head' style='color:#000000'>QTY</font>&nbsp;</td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='center'><font class='White-Style-Head' style='color:#000000'>RATE/UNIT</font></td>"
        HTML &= "<td style='width:70px;' valign='bottom' align='center'><font class='White-Style-Head' style='color:#000000'>QTY</font>&nbsp;</td>"
        HTML &= "<td align='right'  valign='center'><font class='White-Style-Head' style='color:#000000'>AMOUNT</font></td>"
        HTML &= "</tr>"

        Dim Vat As String = ""
        Dim dsConfig As DataSet = Session("Config")
        If (dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(1) = "00") Then
            Vat = CInt(dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(0)).ToString()
        Else
            Vat = dsConfig.Tables(0).Rows(0).Item("Vat").ToString()
        End If

        Dim Value As Double = 0
        Dim ValueVat As Double = 0
        Dim WHT As Double = 0
        Dim row As Integer = 2
        Dim DSItem As New DataTable
        If (PORT = "L") Then
            DSItem = clsGet.GetTemp_Estimate(Booking_no, "")
        Else
            DSItem = clsGet.GetTemp_Estimate(Booking_no, MAgent_no)
        End If
        ViewState("DSItem") = DSItem
        For Each dr As DataRow In DSItem.Rows
            If (CDbl(dr.Item("data4")) > 0.0) Then
                Dim MatName As String = dr.Item("MAT_Name")
                If (row Mod 2) Then
                    HTML &= "<tr>"
                Else
                    HTML &= "<tr style='background-color:#F0F9FB;'>"
                End If
                row += 1
                Dim data1 As String = dr.Item("data1")
                Dim data2 As String = dr.Item("data2")
                Dim data3 As String = dr.Item("data3")
                Dim data4 As String = dr.Item("data4")
                FormatN(data1)
                FormatN(data2)
                ' FormatN(data3)
                FormatN(data4)
                Dim Mat_Code As String = ""
                Try
                    Mat_Code = CInt(dr.Item("Material"))
                Catch ex As Exception
                    Mat_Code = dr.Item("Material")
                End Try
                HTML &= "<td style='width:140px;' valign='top'  align='left'><font class='White-Style' style='color:#000000'>" & Mat_Code & "</font>&nbsp;</td>"
                HTML &= "<td style='width:280px;' align='left'><font class='White-Style' style='color:#000000'>" & MatName & "</font></td>"
                HTML &= "<td style='width:80px;' valign='bottom' align='right'><font class='White-Style' style='color:#000000'>" & data1 & "</font>&nbsp;</td>"
                HTML &= "<td style='width:80px;' valign='bottom' align='right'><font class='White-Style' style='color:#000000'>" & data2 & "</font></td>"
                HTML &= "<td style='width:70px;' valign='bottom' align='center'><font class='White-Style' style='color:#000000'>" & data3 & "</font>&nbsp;</td>"
                HTML &= "<td align='right'  valign='bottom'><font class='White-Style' style='color:#000000'>" & data4 & "</font></td>"
                HTML &= "</tr>"
                Value = Value + CDbl(dr.Item("data4"))
                Dim dt As DataTable = clsGet.Get_MeterailWhithodingTax(dr.Item("Material"))
                If (dt.Rows(0).Item("MAT_WHT") & "" = "01") Or (dt.Rows(0).Item("MAT_WHT") & "" = "02") Or (dt.Rows(0).Item("MAT_WHT") & "" = "03") Then
                    '1%
                    WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                ElseIf (dt.Rows(0).Item("MAT_WHT") & "" = "04") Or (dt.Rows(0).Item("MAT_WHT") & "" = "05") Then
                    '3%
                    WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                ElseIf (dt.Rows(0).Item("MAT_WHT") & "" = "06") Or (dt.Rows(0).Item("MAT_WHT") & "" = "22") Then
                    '5%
                    WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                End If
            End If

        Next


        HTML &= "<tr>"
        'HTML &= "<td style='border-width: 1px 0px 0px 0px;' colspan='5' align='left'>&nbsp;</td>"
        'HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & FormatNumber(Value.ToString("#############0.00")) & "</font></td>"
        'HTML &= "</tr>"


        HTML &= "<td style='width:140px;' valign='top'  align='left'>&nbsp;</td>"
        HTML &= "<td style='width:280px;' align='left'><font class='White-Style' style='color:#000000'>TOTAL SERVICE CHARGE       (EXCLUSIVE OF VAT)</font></td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='right'>&nbsp;</td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='right'>&nbsp;</td>"
        HTML &= "<td style='width:70px;' valign='bottom' align='center'>&nbsp;</td>"
        HTML &= "<td align='right'  valign='bottom'><font class='White-Style' style='color:#000000'>" & FormatNumber(Value.ToString("#############0.00")) & "</font></td>"
        HTML &= "</tr>"

        ValueVat = ((Value * CDbl(Vat)) / 100).ToString("############.00")
        HTML &= "<tr>"
        'HTML &= "<td style='border-width: 0px;' colspan='5' align='right'><font class='White-Style' style='color:#000000'>Vat " & Vat & "%</font>&nbsp;</td>"
        'HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & FormatNumber(ValueVat) & "</font></td>"
        'HTML &= "</tr>"
        HTML &= "<td style='width:140px;' valign='top'  align='left'>&nbsp;</td>"
        HTML &= "<td style='width:280px;' align='right'><font class='White-Style' style='color:#000000'>ADD VAT " & Vat & "%   </font></td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='right'>&nbsp;</td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='right'>&nbsp;</td>"
        HTML &= "<td style='width:70px;' valign='bottom' align='center'>&nbsp;</td>"
        HTML &= "<td align='right'  valign='bottom'><font class='White-Style' style='color:#000000'>" & FormatNumber(ValueVat, 2) & "</font></td>"
        HTML &= "</tr>"


        HTML &= "<tr>"
        'HTML &= "<td style='border-width: 0px;' colspan='5' align='right'><font class='White-Style' style='color:#000000'>รวมประเมินค่าใช้จ่าย</font>&nbsp;</td>"
        'HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & FormatNumber((Value + ValueVat).ToString("###############.00")) & "</font></td>"
        'HTML &= "</tr>"
        HTML &= "<td style='width:140px;' valign='top'  align='left'>&nbsp;</td>"
        HTML &= "<td style='width:280px;' align='left'><font class='White-Style' style='color:#000000'>TOTAL SERVICE CHARGE       (INCLUSIVE OF VAT)</font></td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='right'>&nbsp;</td>"
        HTML &= "<td style='width:80px;' valign='bottom' align='right'>&nbsp;</td>"
        HTML &= "<td style='width:70px;' valign='bottom' align='center'>&nbsp;</td>"
        HTML &= "<td align='right'  valign='bottom'><font class='White-Style' style='color:#000000'>" & FormatNumber((Value + ValueVat).ToString("###############.00"), 2) & "</font></td>"
        HTML &= "</tr>"

        HTML &= "</table>"

        Return HTML
    End Function

    Public Sub HeadReport(ByVal Booking_no As String)
        Dim dt As DataTable = clsGet.Get_BookingOneRecord(Booking_no).Tables(0)
        If (dt.Rows.Count > 0) Then
            lbShip.Text = "SHIP NAME : " & dt.Rows(0).Item("Vehicle_Text")
            lbAgent.Text = "SHIP AGENT : " & dt.Rows(0).Item("MAgent_name")
            lbLoA.Text = "L.O.A.(ft) : " & dt.Rows(0).Item("Vehicle_LOA")
            lbGrt.Text = "GRT : " & dt.Rows(0).Item("Vehicle_GRT")
            lbdWT.Text = "DWT : " & dt.Rows(0).Item("Vehicle_DWT")
            Dim PORT As String = dt.Rows(0).Item("PORT")
            Dim LAYTIME As String = dt.Rows(0).Item("Lay_Time")
            Dim Berthing_Date As String = ""
            Dim Berthing_TimeTo As String = ""
            Dim POB_Date As String = ""
            Dim POB_Time As String = ""
            Dim Date_From As String = dt.Rows(0).Item("Date_From")
            Dim Date_To As String = dt.Rows(0).Item("Date_To")
            Dim Disconnect_Date As String = ""
            Dim Disconnect_to As String = ""

            dt = clsGet.Get_BookingWharf(Booking_no)
            If (dt.Rows.Count > 0) Then
                lbWharf.Text = "WHARF No : " & dt.Rows(0).Item("Wharf")
            Else
                lbWharf.Text = "WHARF No : "
            End If

            dt = clsGet.Get_Load_Unload_Product(Booking_no, "")
            Dim PO As String = "0"
            For Each dr As DataRow In dt.Rows
                Try
                    Disconnect_Date = dr.Item("LU_Disconnect_Date")
                    Disconnect_to = dr.Item("LU_Disconnect_To")
                    If PORT = "L" Then
                        PO = CDbl(PO) + CDbl(dr.Item("LU_SLMT"))
                    Else
                        PO = CDbl(PO) + CDbl(dr.Item("LU_SUMT"))
                    End If
                Catch ex As Exception

                End Try
            Next
            lbPo.Text = "PO : " & PO & " MT"
            If (LAYTIME <> "0") Then
                Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(Booking_no)
                Dim dtProduct As DataTable = clsGet.Get_Booking_Product(Booking_no)
                Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(Booking_no)
                If (dtLogIn.Rows.Count > 0) Then
                    If (PORT = "L") Then

                        Dim Product_no As String = ""
                        Try
                            Dim sort As Integer = 0
                            For Each dr As DataRow In dtProduct.Rows
                                If (CInt(dr.Item("Product_Index") & "") > sort) Then
                                    sort = CInt(dr.Item("Product_Index"))
                                    Product_no = dr.Item("Product_no")
                                End If
                            Next
                        Catch ex As Exception

                        End Try
                        Dim dtLoad As DataTable = clsGet.Get_Load_Unload_Vessel(Booking_no)
                        Dim NOR As String = ""
                        Dim NOR_Time As String = ""
                        Dim POB As String = ""
                        POB_Time = ""
                        If (dtLoad.Rows.Count > 0) Then
                            If (dtLoad.Rows(0).Item("NOR_Date") & "" <> "") Then
                                NOR = dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(3, 2)) & " 20" & dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(6, 2)
                                NOR_Time = dtLoad.Rows(0).Item("NOR_Time") & ""
                            Else
                                NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                            End If
                        Else
                            NOR = ""
                            NOR_Time = ""
                        End If
                        If (dtLogIn.Rows.Count > 0) Then
                            If (dtLogIn.Rows(0).Item("POB_Date") & "" <> "") Then
                                If (dtLogIn.Rows(0).Item("Up_Date") & "" <> "") Then
                                    If (CDate(dtLogIn.Rows(0).Item("POB_Date")) < CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                    ElseIf (CDate(dtLogIn.Rows(0).Item("POB_Date")) = CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                                        If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                            POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                            POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                        ElseIf (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) = CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                            If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(1)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(1))) Then
                                                POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                            Else
                                                POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                            End If
                                        Else
                                            POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                            POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                        End If
                                    Else
                                        POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                        POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                    End If
                                Else
                                    POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                    POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                End If
                            Else
                                POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                            End If
                        Else
                            POB = ""
                            POB_Time = ""
                        End If


                        dtLoad = clsGet.Get_Load_Unload_Product(Booking_no, Product_no)

                        Dim Berthing_DateL As String = dtLogIn.Rows(0).Item("Berthing_Date")
                        Try
                            Try
                                If (CInt(dtLogIn.Rows(0).Item("Berthing_TimeTo").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Berthing_TimeFrom").ToString.Split(":")(0))) Then
                                    Berthing_Date = CDate(Berthing_Date).AddDays(1).ToString("dd MMM", New CultureInfo("en-US")) & " " & Berthing_Date.Split(" ")(2)
                                End If
                            Catch ex As Exception

                            End Try
                        Catch ex As Exception

                        End Try
                        If (dtLoad.Rows.Count > 0) Then
                            LAYTIME = clsGet.ComputeRemainLaytime(Berthing_DateL, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, dtLoad.Rows(0).Item("LU_Disconnect_Date") & "", dtLoad.Rows(0).Item("LU_Disconnect_To") & "", NOR, NOR_Time)
                        Else
                            LAYTIME = clsGet.ComputeRemainLaytime(Berthing_DateL, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, "", "", NOR, NOR_Time)
                        End If

                    Else
                        'Bulk
                        Dim dtProductBulk As DataTable = clsGet.Get_Booking_Product(Booking_no)
                        If (dtProductBulk.Rows.Count > 0) Then
                            Dim chkCoil As Boolean = False
                            For Each dx As DataRow In dtProductBulk.Rows
                                If (dx.Item("Group_no") & "" = "00007") Then
                                    chkCoil = True
                                    Exit For
                                End If
                            Next
                            If (chkCoil) Then
                                Dim LY As Integer = CInt(dsBooking.Tables(0).Rows(0).Item("Lay_Time"))
                                dtProductBulk = clsGet.Get_Load_Unload_Vessel_Product_Detail(Booking_no)
                                If (dtProductBulk.Rows.Count > 0) Then
                                    For Each dr As DataRow In dtProductBulk.Rows
                                        Dim ts = DateDiff("n", dr.Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dr.Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " 20" & dr.Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dr.Item("LU_StartActual_Time"), dr.Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dr.Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " 20" & dr.Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dr.Item("LU_StopActual_Time"))
                                        Dim Hour As String = "0"
                                        Dim chksub As String = ""
                                        Dim Minute As String = "0"
                                        If (LY >= (ts \ 60)) Then
                                            If (LY = (ts \ 60)) Then
                                                If (ts Mod 60) > 0 Then
                                                    chksub = "-"
                                                    Hour = ((ts \ 60) - LY)
                                                    Minute = (ts Mod 60)
                                                Else
                                                    If (ts Mod 60) > 0 Then
                                                        Minute = 60 - (ts Mod 60)
                                                        LY -= 1
                                                    End If
                                                    Hour = LY - (ts \ 60)
                                                End If
                                            Else
                                                If (ts Mod 60) > 0 Then
                                                    Minute = 60 - (ts Mod 60)
                                                    LY -= 1
                                                End If
                                                Hour = LY - (ts \ 60)
                                            End If
                                        Else
                                            chksub = "-"
                                            Hour = ((ts \ 60) - LY)
                                            Minute = (ts Mod 60)
                                        End If
                                        LAYTIME = chksub & Hour & ":" & CInt(Minute).ToString("00")

                                    Next
                                End If
                            End If
                        End If
                    End If
                End If

            End If
            dt = clsGet.Get_Booking_LogSheet_In(Booking_no)
            If (dt.Rows.Count > 0) Then
                Try
                    Dim PERIOD As String = dt.Rows(0).Item("Berthing_Date") & " " & dt.Rows(0).Item("Berthing_TimeFrom")
                    Berthing_Date = dt.Rows(0).Item("Berthing_Date")
                    Berthing_TimeTo = dt.Rows(0).Item("Berthing_TimeTo")
                    POB_Date = dt.Rows(0).Item("POB_Date")
                    POB_Time = dt.Rows(0).Item("POB_Time")
                    dt = clsGet.Get_Booking_LogSheet_Out(Booking_no)
                    PERIOD &= " - " & dt.Rows(0).Item("Last_Date") & " " & dt.Rows(0).Item("Last_Time")
                    lbPilottime.Text = "PERIOD TIME : " & PERIOD
                Catch ex As Exception
                    lbPilottime.Text = ""
                End Try

            Else
                lbPilottime.Text = ""
            End If

            lbLayTime.Text = "LAYTIME : " & LAYTIME
        Else
            lbShip.Text = "SHIP NAME : "
            lbAgent.Text = "SHIP AGENT : "
            lbLoA.Text = "L.O.A.(ft) : "
            lbGrt.Text = "GRT : "
            lbdWT.Text = "DWT : "
            lbPilottime.Text = "PERIOD TIME : "
            lbLayTime.Text = "LAYTIME : 0"
            lbPo.Text = "PO : 0 MT"
            lbWharf.Text = "WHARF No : "
        End If
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub gridsub_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridsub.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridsub.PageIndex <> 0) Then
            Index = Index Mod (gridsub.PageIndex * 10)
        End If
        If e.CommandName = "Booking" Then
            Dim _Date As String = ""
            If (gridsub.DataKeys(Index).Values("Date_From") & "" <> "") Then
                If (gridsub.DataKeys(Index).Values("Date_From") & "" = gridsub.DataKeys(Index).Values("Date_To") & "") Then
                    _Date = gridsub.DataKeys(Index).Values("Date_To")
                Else
                    _Date = gridsub.DataKeys(Index).Values("Date_From").ToString.Substring(0, 2) & "-" & gridsub.DataKeys(Index).Values("Date_To")
                End If
            End If
            panelMain.Visible = False
            PanelSub.Visible = True
            panelBooking.Visible = True
            panelEstimate.Visible = False
            Dim dtwharf As DataTable = clsGet.Get_BookingWharf_ForMYBooking(gridsub.DataKeys(Index).Values("Booking_no") & "")
            Dim Wharf As String = ""
            Dim Plan As String = ""
            Dim Depart As String = ""
            If (dtwharf.Rows.Count = 1) Then
                Wharf = dtwharf.Rows(0).Item("Wharf") & ""
                Plan = dtwharf.Rows(0).Item("Date_From") & " - " & dtwharf.Rows(0).Item("TimeStart")
                Depart = dtwharf.Rows(0).Item("Date_To") & " - " & dtwharf.Rows(0).Item("TimeEnd")
            End If
            GenBOoking(gridsub.DataKeys(Index).Values("Booking_no") & "", gridsub.DataKeys(Index).Values("MAgent_no") & " - " & gridsub.DataKeys(Index).Values("MAgent_name"), _Date, gridsub.DataKeys(Index).Values("Vehicle_Text") & "", Wharf, Plan, Depart)
        ElseIf (e.CommandName = "Estimate") Then
            panelMain.Visible = False
            PanelSub.Visible = True
            panelBooking.Visible = False
            panelEstimate.Visible = True
            LiEstimate.Text = GetActual(gridsub.DataKeys(Index).Values("Booking_no") & "", gridsub.DataKeys(Index).Values("PORT") & "", gridsub.DataKeys(Index).Values("MAgent_no") & "")
        ElseIf (e.CommandName = "Payment") Then

        End If
    End Sub

    Private Sub gridsub_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridsub.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim imgBooking As ImageButton = CType(e.Row.FindControl("imgBooking"), ImageButton)
            Dim imgEstimate As ImageButton = CType(e.Row.FindControl("imgEstimate"), ImageButton)
            Dim imgPayment As ImageButton = CType(e.Row.FindControl("imgPayment"), ImageButton)
            Dim dt As DataTable
            If (gridsub.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                dt = clsGet.GetTemp_Estimate(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", "")
            Else
                If (Session("Role") & "" = "00002") Then
                    dt = clsGet.GetTemp_Estimate(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no"))
                Else
                    dt = clsGet.GetTemp_Estimate(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", "")
                End If
            End If
            If (dt.Rows.Count > 0) Then
                imgEstimate.ImageUrl = "../Image/Correct.png"
            Else
                Dim dtbooking As DataTable = clsGet.Get_BookingOneRecord(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "").Tables(0)
                If (dtbooking.Rows.Count > 0) Then
                    If (dtbooking.Rows(0).Item("Marketing_approve") & "" = "") Then
                        imgEstimate.ImageUrl = "../Image/NotCorrect.png"
                    Else
                        imgEstimate.ImageUrl = "../Image/Correct.png"
                    End If
                Else
                    imgEstimate.ImageUrl = "../Image/NotCorrect.png"
                End If
            End If

            If (gridsub.DataKeys(e.Row.RowIndex).Values("Date_From") & "" <> "") Then
                If (gridsub.DataKeys(e.Row.RowIndex).Values("Date_From") & "" = gridsub.DataKeys(e.Row.RowIndex).Values("Date_To") & "") Then
                    e.Row.Cells(2).Text = gridsub.DataKeys(e.Row.RowIndex).Values("Date_To")
                Else
                    e.Row.Cells(2).Text = gridsub.DataKeys(e.Row.RowIndex).Values("Date_From").ToString.Substring(0, 2) & "-" & gridsub.DataKeys(e.Row.RowIndex).Values("Date_To")
                End If
            End If
            If (gridsub.DataKeys(e.Row.RowIndex).Values("Status") & "" = "N") Then
                imgBooking.ImageUrl = "../Image/NotCorrect.png"
                imgPayment.ImageUrl = "../Image/NotCorrect.png"
            Else
                imgBooking.ImageUrl = "../Image/Correct.png"
                dt = clsGet.Get_BookingOneRecord(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "").Tables(0)
                If (dt.Rows.Count > 0) Then
                    If (dt.Rows(0).Item("Payin") & "" = "0") Then
                        If (Session("Role") & "" = "00002") Then
                            If (clsGet.GetPayinAdvance(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no"))) Then
                                imgPayment.ImageUrl = "../Image/Correct.png"
                            Else
                                imgPayment.ImageUrl = "../Image/NotCorrect.png"
                            End If
                        Else
                            If (clsGet.GetPayinAdvance(gridsub.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", dt.Rows(0).Item("MAgent_no") & "")) Then
                                imgPayment.ImageUrl = "../Image/Correct.png"
                            Else
                                imgPayment.ImageUrl = "../Image/NotCorrect.png"
                            End If
                        End If
                    ElseIf (dt.Rows(0).Item("Status") & "" = "FN") Then
                        imgPayment.ImageUrl = "../Image/Correct.png"
                    Else
                        imgPayment.ImageUrl = "../Image/NotCorrect.png"
                    End If
                Else
                    imgPayment.ImageUrl = "../Image/NotCorrect.png"
                End If
            End If

        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridsub.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridsub.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridsub.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                    ddlPage.Items(i).Attributes.Add("Style", "height:60px")
                Next

            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridsub.PageCount.ToString()
            End If
        End If
    End Sub

    Private Sub GenBOoking(ByVal Booking_no As String, ByVal Agent As String, ByVal Laycan As String, ByVal Vessel As String, ByVal Wharf As String, ByVal Plan As String, ByVal Depart As String)
        Dim dt As DataTable = clsGet.Get_Booking_Product(Booking_no)
        gridProduct.DataSource = dt
        gridProduct.DataBind()
        lbBooking.Text = Booking_no
        lbVessel.Text = Vessel
        lbLaycan.Text = Laycan
        lbSoldTo.Text = Agent
        lbPlan.Text = Plan
        lbDepart.Text = Depart
        lbWharfMyBOoking.Text = Wharf
    End Sub

    Private Sub gridBooking_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridBooking.RowEditing

    End Sub

    Private Sub gridsub_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridsub.RowEditing

    End Sub

    Public Sub imgCloseActual_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgCloseActual.Click
        LoadDataMyBooking("", "", "", "")
    End Sub

    Private Sub gridProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridProduct.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "L") Then
                e.Row.Cells(0).Text = "Load"
            Else
                e.Row.Cells(0).Text = "Disch"
            End If
        End If
    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Try
            If Not (txtVessel.Text.Trim() = "") Then
                Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
                If (ds.Rows.Count > 0) Then
                    'พบเรือ
                    If (UpdateVessel(txtVessel.Text.Split("-")(0))) Then
                        'Update Vessel
                        ds = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))

                        'Bind Data VEHICLE Detail
                        lbLOASHOW.Text = (CDbl(ds.Rows(0).Item("VEH_LENGTH")) * 3.281).ToString("############0.00")
                        lbDWTSHow.Text = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
                        lbDraft.Text = (CDbl(ds.Rows(0).Item("DRAFT")) * 3.281).ToString("############0.00")
                        lbNation.Text = ds.Rows(0).Item("REG_CNTRY")
                        If Not ((ds.Rows(0).Item("STCMNR") & "").ToString().Trim() = "") Then
                            Try
                                lbGRTSHow.Text = ds.Rows(0).Item("STCMNR").ToString().Replace("GRT", "").Replace("=", "").Replace("MT", "")
                            Catch ex As Exception

                            End Try
                        End If
                        If (lbLOASHOW.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล LOA !!');", True)
                            Exit Sub
                        End If
                        If (lbDWTSHow.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล DWT !!');", True)
                            Exit Sub
                        End If
                        If (lbDraft.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Draft !!');", True)
                            Exit Sub
                        End If
                        If (lbNation.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล FLAG !!');", True)
                            Exit Sub
                        End If
                        If (lbGRTSHow.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล GRT !!');", True)
                            Exit Sub
                        End If
                        PanelVEHICLE_IN_DETAIL.Visible = True
                    End If

                Else
                    'ไม่พบเรือ
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเรือไม่ถูกต้อง!!');", True)
                End If
            Else
                'ยังไม่ระบุข้อมูลเรือ
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเรือ!!');", True)
            End If

        Catch ex As Exception
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถทำการเชื่อมต่อ SAP ได้!!');", True)
        End Try
    End Sub

    Private Sub btnSearchOUT_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchOUT.Click
        If (txtLOA.Text.Trim = "") Or (txtDWT.Text.Trim() = "") Or (txtDraft.Text.Trim() = "") Or (txtGRT.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุข้อมูลเรือให้ครบ !!');", True)
            Exit Sub
        End If
        If Not (txtVesselOUT.Text.Trim() = "") Then
            txtVesselOUT.Enabled = False
            radioVehicle.Enabled = False
            txtLOA.Enabled = False
            txtDWT.Enabled = False
            txtDraft.Enabled = False
            txtGRT.Enabled = False
            txtid.Enabled = False
            ddlNation.Enabled = False
            btnSearchOUT.Visible = False
            radioPort.Enabled = False
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเรือ!!');", True)
        End If
    End Sub
    Private Sub radioDemurrage_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioDemurrage.SelectedIndexChanged
        If (radioDemurrage.SelectedValue = "Y") Then
            rowLaytime.Visible = True
            txtDemurrage.Text = "0"
            txtLayTime.Text = "0"
        Else
            rowLaytime.Visible = False
            txtDemurrage.Text = "0"
            txtLayTime.Text = "0"
        End If
    End Sub
    Private Sub btnProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProduct.Click
        If (radioPort.SelectedValue & "" = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุท่าเรือ!!');", True)
            Exit Sub
        End If
        Session("PORT_PRODUCT") = radioPort.SelectedValue
        ModalPopupExtender5.Show()
    End Sub


    Private Sub btnSaveProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveProduct.Click
        Dim dt As DataTable = Session("Product_popup")
        gridProductShow.DataSource = dt
        gridProductShow.DataBind()
    End Sub

    Private Sub btnSaveUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveUpload.Click
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()
    End Sub
    Private Function UpdateVessel(ByVal Vehicle As String) As Boolean
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim dsConfig As DataSet = Session("Config")
        Dim Im_Veh_From As String = Vehicle
        Dim Im_Veh_To As String = ""
        Dim Date_From As String = ""
        Dim Date_To As String = ""

        Dim Ex_Subrc As Integer = 0

        Dim Veh_Table As New SAP_IPORT.ZBAPI_VEH_INPUTTable
        Dim Veh_Infor As New SAP_IPORT.ZBAPI_VEH_INFORTable
        Dim Veh_Unit As New SAP_IPORT.ZBAPI_VEH_UNITTable
        SAP_Data.Zbapi_Iport_Vehicle_Master(Date_From, Date_To, Im_Veh_From, Im_Veh_To, Ex_Subrc, Veh_Table, Veh_Infor, Veh_Unit)
        ClassSAP.SAP_CLOSE(SAP_Data)
        If (Veh_Unit.Count > 0) Or (Veh_Infor.Count > 0) Then
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase()
            Dim clsFc As New ClassFunction()
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Try

                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                For i As Integer = 0 To Veh_Infor.Count - 1
                    If (clsFc.UPDATEVehicle(Veh_Infor.Item(i).Vehicle, Veh_Infor.Item(i).Veh_Text, Veh_Infor.Item(i).Owner, Veh_Infor.Item(i).Reg_Cntry, Veh_Infor.Item(i).Veh_Type, Veh_Infor.Item(i).Veh_Length, Veh_Infor.Item(i).Veh_Width, Veh_Infor.Item(i).Veh_Height, Veh_Infor.Item(i).Draft, Veh_Infor.Item(i).Dim_Uom, Veh_Infor.Item(i).Veh_Unlwgt, Veh_Infor.Item(i).Veh_Unlwgt_C, Veh_Infor.Item(i).Veh_Maxwgt, Veh_Infor.Item(i).Veh_Maxwgt_C, Veh_Infor.Item(i).Wgt_Uom, Veh_Infor.Item(i).Veh_Maxvol, Veh_Infor.Item(i).Veh_Maxvol_C, Veh_Infor.Item(i).Vol_Uom, Veh_Infor.Item(i).Stcmnr, Veh_Infor.Item(i).Veh_Nrtus, conn, tran) = 0) Then
                        If (clsFc.InsertVehicle(Veh_Infor.Item(i).Vehicle, Veh_Infor.Item(i).Veh_Text, Veh_Infor.Item(i).Owner, Veh_Infor.Item(i).Reg_Cntry, Veh_Infor.Item(i).Veh_Type, Veh_Infor.Item(i).Veh_Length, Veh_Infor.Item(i).Veh_Width, Veh_Infor.Item(i).Veh_Height, Veh_Infor.Item(i).Draft, Veh_Infor.Item(i).Dim_Uom, Veh_Infor.Item(i).Veh_Unlwgt, Veh_Infor.Item(i).Veh_Unlwgt_C, Veh_Infor.Item(i).Veh_Maxwgt, Veh_Infor.Item(i).Veh_Maxwgt_C, Veh_Infor.Item(i).Wgt_Uom, Veh_Infor.Item(i).Veh_Maxvol, Veh_Infor.Item(i).Veh_Maxvol_C, Veh_Infor.Item(i).Vol_Uom, Veh_Infor.Item(i).Stcmnr, Veh_Infor.Item(i).Veh_Nrtus, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                Next
                For i As Integer = 0 To Veh_Unit.Count - 1
                    If (clsFc.UPDATEVehicle_infor(Veh_Unit.Item(i).Vehicle, Veh_Unit.Item(i).Tu_Type, Veh_Unit.Item(i).Tu_Class, Veh_Unit.Item(i).Tu_Mode, Veh_Unit.Item(i).Tu_Length, Veh_Unit.Item(i).Tu_Width, Veh_Unit.Item(i).Tu_Height, Veh_Unit.Item(i).Dim_Uom, Veh_Unit.Item(i).Tu_Unlwgt, Veh_Unit.Item(i).Tu_Unlwgt_C, Veh_Unit.Item(i).Tu_Maxwgt, Veh_Unit.Item(i).Tu_Maxwgt_C, Veh_Unit.Item(i).Wgt_Uom, Veh_Unit.Item(i).Tu_Maxvol, Veh_Unit.Item(i).Tu_Maxvol_C, Veh_Unit.Item(i).Vol_Uom, conn, tran) = 0) Then
                        If (clsFc.InsertVehicle_infor(Veh_Unit.Item(i).Vehicle, Veh_Unit.Item(i).Tu_Type, Veh_Unit.Item(i).Tu_Class, Veh_Unit.Item(i).Tu_Mode, Veh_Unit.Item(i).Tu_Length, Veh_Unit.Item(i).Tu_Width, Veh_Unit.Item(i).Tu_Height, Veh_Unit.Item(i).Dim_Uom, Veh_Unit.Item(i).Tu_Unlwgt, Veh_Unit.Item(i).Tu_Unlwgt_C, Veh_Unit.Item(i).Tu_Maxwgt, Veh_Unit.Item(i).Tu_Maxwgt_C, Veh_Unit.Item(i).Wgt_Uom, Veh_Unit.Item(i).Tu_Maxvol, Veh_Unit.Item(i).Tu_Maxvol_C, Veh_Unit.Item(i).Vol_Uom, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If

                Next
                If (Date_To <> "") Then
                    If (clsFc.UpdateVehicle_Date(Date_To, conn, tran) < 1) Then
                        condition = False
                    End If
                End If

                If (condition) Then
                    clsDB.CommitTran(tran)
                    conn.Close()
                    Application.UnLock()
                    Veh_Infor.Clear()
                    Veh_Unit.Clear()
                    conn.Dispose()

                    Return True
                Else
                    clsDB.RollBackTran(tran)
                    conn.Close()
                    Application.UnLock()
                    Veh_Infor.Clear()
                    Veh_Unit.Clear()
                    conn.Dispose()
                    Return False
                End If
            Catch ex As Exception
                clsDB.RollBackTran(tran)
                conn.Close()
                Application.UnLock()
                Veh_Infor.Clear()
                Veh_Unit.Clear()
                conn.Dispose()
                Return False
            End Try

        Else
            Return True
        End If
    End Function

    Private Sub radioVehicle_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioVehicle.SelectedIndexChanged
        If (radioVehicle.SelectedValue = "0") Then
            'In
            txtVessel.Text = txtVesselOUT.Text
            PanelVEHICLE_IN.Visible = True
            PanelVEHICLE_OUT.Visible = False
            PanelVEHICLE_IN_DETAIL.Visible = True
            lbFT1.Text = "FT"
            lbFT2.Text = "FT"
        Else
            'OUT
            txtVesselOUT.Text = txtVessel.Text
            PanelVEHICLE_IN_DETAIL.Visible = False
            PanelVEHICLE_IN.Visible = False
            PanelVEHICLE_OUT.Visible = True
            lbFT1.Text = "M"
            lbFT2.Text = "M"
        End If
    End Sub

    Private Sub gridfile_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridfile.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (e.CommandName = "cmddelete") Then
            Dim dt As DataTable = Session("Q88")
            System.IO.File.Delete(Server.MapPath("../Uploads/") + dt.Rows(Index).Item("File_nameGuid"))
            dt.Rows(Index).Delete()
            dt.AcceptChanges()
            Session("Q88") = dt
            gridfile.DataSource = dt
            gridfile.DataBind()
        ElseIf (e.CommandName = "Select") Then
            Dim FileName As String = gridfile.DataKeys(Index).Values("File_name")
            Dim FileGen As String = gridfile.DataKeys(Index).Values("File_nameGuid") & gridfile.DataKeys(Index).Values("File_Type")
            ' Dim FileType As String = gridfile.DataKeys(Index).Values("File_Type")
            Dim ContentType As String = gridfile.DataKeys(Index).Values("File_ContentType").ToString().Replace(".", "")
            Dim script As String = "window.open('IPORTDownloadfile.aspx?str2=" + FileGen + "&str3=." + ContentType + "&str4=" + FileName + "','_blank','left=0,top=0,location=no,menubar= no,resizable=yes,scrollbars=no,toolbar=no,status=no,width=100px,height=50px');"
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", script, True)
        End If
    End Sub

    Private Sub gridfile_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridfile.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim ImgDelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
            If (ViewState("EditBooking") & "" <> "") Then
                ImgDelete.Visible = False
            End If
        End If
    End Sub

    Private Sub gridProductShow_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridProductShow.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "cmddelete" Then
            Dim ds As DataTable = Session("Product_popup")
            ds.Rows(Index).Delete()
            ds.AcceptChanges()
            If (ds.Rows.Count = 0) Then
                ds = CreateDatasetProduct()
            End If
            Session("Product_popup") = ds
            gridProductShow.PageIndex = 0
            gridProductShow.DataSource = Session("Product_popup")
            gridProductShow.DataBind()
        ElseIf e.CommandName = "cmdedit" Then
            Session("IndexProduct") = Index
            Session("PORT_PRODUCT") = radioPort.SelectedValue
            ModalPopupExtender5.Show()
        End If
    End Sub


    Public Function CreateDatasetProduct() As DataTable
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim dr As DataRow
        ds.Tables.Add(dt)
        dt.Columns.Add("Product_no", GetType(String))
        dt.Columns.Add("Product_name", GetType(String))
        dt.Columns.Add("Product_Amount", GetType(String))
        dt.Columns.Add("Product_Event", GetType(String))
        dt.Columns.Add("Product_Description", GetType(String))
        dt.Columns.Add("Product_Unit", GetType(String))
        dt.Columns.Add("Group_name", GetType(String))
        dt.Columns.Add("Group_no", GetType(String))
        dt.Columns.Add("Product_BUYER_no", GetType(String))
        dt.Columns.Add("Product_BUYER_name", GetType(String))
        dt.Columns.Add("Product_SELLER_no", GetType(String))
        dt.Columns.Add("Product_SELLER_name", GetType(String))
        dt.Columns.Add("LoadDestination", GetType(String))
        dt.Columns.Add("DischDestination", GetType(String))
        dt.Columns.Add("DestinationShow", GetType(String))
        dt.Columns.Add("Owner_Product_no", GetType(String))
        dt.Columns.Add("Owner_Product_name", GetType(String))
        dr = ds.Tables(0).NewRow
        dr.Item("Product_no") = ""
        dr.Item("Product_name") = ""
        dr.Item("Product_Amount") = ""
        dr.Item("Product_Event") = ""
        dr.Item("Product_Description") = ""
        dr.Item("Product_Unit") = ""
        dr.Item("Group_name") = ""
        dr.Item("Group_no") = ""
        dr.Item("Product_BUYER_no") = ""
        dr.Item("Product_BUYER_name") = ""
        dr.Item("Product_SELLER_no") = ""
        dr.Item("Product_SELLER_name") = ""
        dr.Item("LoadDestination") = ""
        dr.Item("DischDestination") = ""
        dr.Item("DestinationShow") = ""
        dr.Item("Owner_Product_no") = ""
        dr.Item("Owner_Product_name") = ""
        ds.Tables(0).Rows.Add(dr)
        ds.Tables(0).AcceptChanges()
        Return ds.Tables(0)
    End Function

    Private Sub gridProductShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridProductShow.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim ImgDelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
            Dim ImgEdit As ImageButton = CType(e.Row.FindControl("imgedit"), ImageButton)
            Dim dt As DataTable = clsGet.Get_Booking_Product(ViewState("PreBooking"))
            For Each dr As DataRow In dt.Rows
                If (dr.Item("Product_no") = gridProductShow.DataKeys(e.Row.RowIndex).Values("Product_no")) Then
                    ImgDelete.Visible = False
                    Exit For
                End If
            Next
            If (gridProductShow.DataKeys(e.Row.RowIndex).Values("Product_name") & "" = "") Then
                ImgDelete.Visible = False
                ImgEdit.Visible = False
            End If
            If (ViewState("EditBooking") & "" <> "") Then
                ImgDelete.Visible = False
                ImgEdit.Visible = False
            End If
            If (gridProductShow.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "L") Then
                e.Row.Cells(0).Text = "Load"
            ElseIf (gridProductShow.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "D") Then
                e.Row.Cells(0).Text = "Disch"
            ElseIf (gridProductShow.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "R") Then
                e.Row.Cells(0).Text = "Load(IRPC)"
            ElseIf (gridProductShow.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "I") Then
                e.Row.Cells(0).Text = "Disch(IRPC)"
            End If
            If (gridProductShow.DataKeys(e.Row.RowIndex).Values("Group_no") & "" = "0000000000") Then
                e.Row.BackColor = Drawing.Color.Red
            End If
        End If
    End Sub

    Private Sub gridProductShow_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridProductShow.RowEditing

    End Sub

    Private Sub LoadDefault_MAT(ByVal National As String, ByVal TypeBuy As String, ByVal Load As String, ByVal Disch As String, ByVal MaterialB As String, ByVal VesselNational As String)
        Session("MAT_USE") = clsGet.Get_MeterailDefault("", True, "", radioPort.SelectedValue, National, TypeBuy, Load, Disch, MaterialB, VesselNational, "")
        gridTariff.PageIndex = 0
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()
    End Sub
    Private Function CheckParameter() As Boolean
        If (txtDate.Text = "") Then
            Return False
        End If
        If (txtDateTo.Text = "") Then
            Return False
        End If
        If (radioPort.SelectedIndex = -1) Then
            Return False
        End If
        If (raioType.SelectedValue = "") Then
            Return False
        End If
        If (raioType.SelectedValue = "O") Then
            If (radioTypeBuy.SelectedValue = "") Then
                Return False
            End If
        End If
        Return True
    End Function
    Private Function ComputeMAT() As Boolean
        If (CheckParameter()) Then
            If (CDate(txtDate.Text) > CDate(txtDateTo.Text)) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลวันที่เข้า ไม่ถูกต้อง!!');", True)
                Return False
            End If
            If (chkFO.Checked) Then
                If (txtFO.Text.Trim() = "") Or (txtFO.Text.Trim() = "0") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุจำนวนคันรถของ Bunker FO !!');", True)
                    Return False
                End If
            End If
            If (chkDO.Checked) Then
                If (txtDO.Text.Trim() = "") Or (txtDO.Text.Trim() = "0") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุจำนวนคันรถของ Bunker DO !!');", True)
                    Return False
                End If
            End If
            If (txtid.Text.Split("-")(0) = "999999999") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถให้ IRPC เป็น Main Agent ได้ !!');", True)
                Return False
            End If
            If (txtAgent.Text.Split("-")(0) = "999999999") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถให้ IRPC เป็น Sub Agent ได้  !!');", True)
                Return False
            End If
            Dim National As String = ""
            Dim TypeBuy As String = ""
            If (radioVehicle.SelectedValue = "I") Then
                National = "T"
            Else
                National = "O"
                TypeBuy = radioTypeBuy.SelectedValue
            End If
            Dim Load As String = ""
            Dim Disch As String = ""
            Dim MaterailB As String = ""
            Dim VesselNation As String = ""
            Dim dt As DataTable = Session("Product_popup")
            For Each dr As DataRow In dt.Rows
                Dim sLoad As String = ""
                Dim sDisch As String = ""
                Dim sLoadIRPC As String = ""
                Dim sDischIRPC As String = ""
                Select Case dr.Item("Product_Event") & ""
                    Case "L" : Load = "Y"
                        sLoad = "Y"
                    Case "D" : Disch = "Y"
                        sDisch = "Y"
                End Select
                'If (raioType.SelectedValue = "O") Then
                '    Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & raioType.SelectedValue & "$" & radioTypeBuy.SelectedValue
                'Else
                '    Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & raioType.SelectedValue & "$" & ""
                'End If

                Dim dtMat As DataTable = clsGet.Get_Meterail_ProductMaterial(dr.Item("Product_no"), sLoad, sDisch, sLoadIRPC, sDischIRPC)
                For Each drMat As DataRow In dtMat.Rows
                    If (drMat.Item("Material") <> "") Then
                        MaterailB = ",'" & drMat.Item("Material") & "'"
                    End If
                Next
            Next
            If (radioVehicle.SelectedValue = "0") Then
                If lbNation.Text = "TH" Then
                    VesselNation = "T"
                Else
                    VesselNation = "O"
                End If
            Else
                VesselNation = ddlNation.SelectedValue
            End If
            If (radioPort.SelectedValue = "B") Then
                Dim Productchk As Boolean = True
                If (gridProduct.Rows.Count < 2) Then
                    Try
                        If (gridProduct.DataKeys(0).Item("Product_no") & "" = "") Then
                            Productchk = False
                        End If
                    Catch ex As Exception
                        Productchk = False
                    End Try
                End If
                If (Productchk) Then
                    Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
                    For i As Integer = 0 To Owner.Length - 1
                        gridTariff.Columns(4 + i).Visible = True
                        gridTariff.Columns(4 + i).HeaderText = Owner(i).Split("฿")(1)
                    Next
                    btnProduct.Enabled = False
                    gridProduct.Columns(11).Visible = False
                End If

            End If
            LoadDefault_MAT(National, TypeBuy, Load, Disch, MaterailB, VesselNation)
            If (Session("Role") & "" = "00002") Then
                txtDate.Enabled = False
                ImgDate.Enabled = False
                txtDateTo.Enabled = False
                ImgDateTo.Enabled = False
                txtDateBooking.Enabled = False
                txtTimeBooking.Enabled = False
                btnProduct.Enabled = False
            End If

            Return True
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุข้อมูลให้ครบ!!');", True)
            Return False
        End If
    End Function

    Private Sub btnSaveBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveBooking.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()
        Dim Booking As String = ""
        ViewState("EditBooking") = ""
        'คำนวณ Tairff
        If Not (ComputeMAT()) Then
            Exit Sub
        End If
        Booking = ViewState("PreBooking")

        Dim dsProduct As DataTable = Session("Product_popup")
        For Each dr As DataRow In dsProduct.Rows
            If (dr.Item("Product_Buyer_no") & "" = "") And (dr.Item("Product_Seller_no") & "" = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุข้อมูลสินค้าให้ครบถ้วน!!');", True)
                Exit Sub
            End If
        Next


        Dim StandardTimePlus As String = "0"
        If chkFO.Checked Then
            StandardTimePlus = ((CInt(txtFO.Text) * 45) \ 60).ToString() & "." & ((CInt(txtFO.Text) * 45) Mod 60).ToString("00")
        End If
        If (chkDO.Checked) Then
            StandardTimePlus = (CDbl(StandardTimePlus) + CDbl(((CInt(txtDO.Text) * 45) \ 60).ToString() & "." & ((CInt(txtDO.Text) * 45) Mod 60).ToString("00"))).ToString("#########.00")
        End If
        If (txtWater.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Water กรณีไม่มีการใช้กรุณาระบุเป็น 0!!');", True)
            Exit Sub
        End If
        If (txtElectricity.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Electricity กรณีไม่มีการใช้กรุณาระบุเป็น 0!!');", True)
            Exit Sub
        End If
        If (txtDemurrage.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Demurrage กรณีไม่มีการใช้กรุณาระบุเป็น 0!!');", True)
            Exit Sub
        End If

        Dim dtQ88 As DataTable = Session("Q88")
        Dim chkQ88 As Boolean = True
        For Each dr As DataRow In dtQ88.Rows
            If (dr.Item("Upload_Type") = "Q88") Then
                chkQ88 = False
                Exit For
            End If
        Next
        If (chkQ88) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการแนบเอกสาร Q88!!');", True)
            Exit Sub
        End If
        If (txtWater.Text.Trim() <> "0") Then
            Dim dst As DataSet = Session("MAT_USE")
            Dim cNew As Boolean = True
            For Each dr As DataRow In dst.Tables(0).Rows
                If (dr.Item("MATERIAL") = "WP") Then
                    dr.Item("Count") = txtWater.Text
                    dst.AcceptChanges()
                    cNew = False
                    Exit For
                End If
            Next
            If (cNew) Then
                Dim Plant As String = ""
                If (radioPort.SelectedValue = "L") Then
                    Plant = "1103"
                Else
                    Plant = "1104"
                End If
                Dim dtMat As DataSet = clsGet.Get_MeterailDefault("WP", False, "''", "", "", "", "", "", "", "", Plant)
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dst.Tables(0).NewRow()
                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL") & ""
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line") & ""
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = txtWater.Text
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_ComputeM") = "Y"
                    dst.Tables(0).Rows.Add(dr)
                    dst.AcceptChanges()
                    Session("MAT_USE") = dst
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ท่าเรือนี้ไม่ได้ทำการจำหน่ายน้ำ!!');", True)
                    Exit Sub
                End If
            End If


        End If
        If (txtElectricity.Text.Trim() <> "0") Then
            Dim dst As DataSet = Session("MAT_USE")
            Dim cNew As Boolean = True
            For Each dr As DataRow In dst.Tables(0).Rows
                If (dr.Item("MATERIAL") = "ELEC.POWER") Then
                    dr.Item("Count") = txtWater.Text
                    dst.AcceptChanges()
                    cNew = False
                    Exit For
                End If
            Next
            If (cNew) Then
                Dim Plant As String = ""
                If (radioPort.SelectedValue = "L") Then
                    Plant = "1103"
                Else
                    Plant = "1104"
                End If
                Dim dtMat As DataSet = clsGet.Get_MeterailDefault("ELEC.POWER", False, "''", "", "", "", "", "", "", "", Plant)
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dst.Tables(0).NewRow()
                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL") & ""
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line") & ""
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = txtElectricity.Text
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_ComputeM") = "Y"
                    dst.Tables(0).Rows.Add(dr)
                    dst.AcceptChanges()
                    Session("MAT_USE") = dst
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ท่าเรือนี้ไม่ได้ทำการจำหน่ายไฟฟ้า!');", True)
                    Exit Sub
                End If
            End If
        End If


        Session("StandardTimePlus") = CInt(StandardTimePlus)
        ' Dim dsProduct As DataTable = Session("Product_popup")
        Dim ProductName As String = ""
        Dim ProductAmount As Double = 0.0
        Dim ProductAmountByLine As String = ""
        Dim ProductAmountByProduct As String = ""
        Dim ProductType As String = ""
        Dim ProductBuyer As String = ""
        Dim ProductSeller As String = ""
        For Each dr As DataRow In dsProduct.Rows
            If (dr.Item("Product_name") & "" <> "") Then
                ProductName &= "," & dr.Item("Product_name")
                ProductAmountByLine &= "," & dr.Item("Product_Amount")
                ProductAmount = ProductAmount + (CDbl(dr.Item("Product_Amount")))
                ProductType &= "," & dr.Item("Product_Unit")
                ProductBuyer &= "," & dr.Item("Product_BUYER_name")
                ProductSeller &= "," & dr.Item("Product_SELLER_name")
                ProductAmountByProduct &= dr.Item("Product_name") & "฿" & dr.Item("Product_Amount") & "฿"
            End If
        Next
        If (ProductName.Length > 0) Then
            ProductName = ProductName.Substring(1, ProductName.Length - 1)
            ProductAmountByLine = ProductAmountByLine.Substring(1, ProductAmountByLine.Length - 1)
            ProductType = ProductType.Substring(1, ProductType.Length - 1)
            ProductBuyer = ProductBuyer.Substring(1, ProductBuyer.Length - 1)
            ProductSeller = ProductSeller.Substring(1, ProductSeller.Length - 1)
        End If

        ViewState("Product_NameAmount") = ProductName & "$" & ProductAmount & "$" & ProductType & "$" & ProductBuyer & "$" & ProductSeller
        If (radioVehicle.SelectedValue = "0") Then
            Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
            If (ds.Rows.Count > 0) Then
                Dim NameAgent As String = ""
                Dim CodeAgent As String = ""
                If (txtid.Text.Trim() <> "") Then
                    Dim AgentLoops() As String = txtid.Text.Split("-")
                    For i As Integer = 0 To AgentLoops.Length - 1
                        If (i <> 0) Then
                            NameAgent &= "-" & AgentLoops(i).ToString()
                        End If
                    Next
                    CodeAgent = txtid.Text.Split("-")(0)
                    NameAgent = txtid.Text.Split("-")(0) & "-" & NameAgent.Substring(1, NameAgent.Length - 1)
                End If
                Dim tVessel As String = ""
                Dim AgentLoop() As String = txtVessel.Text.Split("-")
                For i As Integer = 0 To AgentLoop.Length - 1
                    If (i <> 0) Then
                        tVessel &= "-" & AgentLoop(i).ToString()
                    End If
                Next
                Dim Nation As String = ""
                If lbNation.Text = "TH" Then
                    Nation = "T"
                Else
                    Nation = "O"
                End If
                tVessel = tVessel.Substring(1, tVessel.Length - 1)
                Session("Value") = NameAgent & "$" & tVessel & "$" & ProductName & "$" & lbdWT.Text & "$" & lbLoA.Text & "$" & ProductAmount & "$" & lbDraft.Text & "$Draft$" & raioType.SelectedValue & "$" & radioTypeBuy.SelectedValue & "$" & Nation & "$" & lbGrt.Text & "$" & radioPort.SelectedValue & "$" & ProductAmountByProduct & "$" & CodeAgent
                '  Session("Value") = lbLOA.Text & "$" & lbDWT.Text & "$" & lbDraft.Text & "$" & lbGRT.Text & "$" & tVessel & "$" & NameAgent & "$Draft" & "$" & ProductName & "$" & ProductAmount & "$" & ProductAmountByProduct & "$" & lbNation.Text & "$" & raioType.SelectedValue & "$" & ViewState("Status")
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเรือไม่ถูกต้อง!!');", True)
                Exit Sub
            End If
        Else
            Dim nation As String = "XX"
            nation = ddlNation.SelectedValue
            Dim NameAgent As String = ""
            Dim CodeAgent As String = ""
            If (txtid.Text.Trim() <> "") Then
                Dim AgentLoops() As String = txtid.Text.Split("-")
                For i As Integer = 0 To AgentLoops.Length - 1
                    If (i <> 0) Then
                        NameAgent &= "-" & AgentLoops(i).ToString()
                    End If
                Next
                CodeAgent = txtid.Text.Split("-")(0)
                NameAgent = NameAgent.Substring(1, NameAgent.Length - 1)
            End If
            Session("Value") = NameAgent & "$" & txtVesselOUT.Text & "$" & ProductName & "$" & txtDWT.Text & "$" & txtLOA.Text & "$" & ProductAmount & "$" & txtDraft.Text & "$Draft$" & raioType.SelectedValue & "$" & radioTypeBuy.SelectedValue & "$" & nation & "$" & txtGRT.Text & "$" & radioPort.SelectedValue & "$" & ProductAmountByProduct & "$" & CodeAgent
            ' Session("Value") = txtLOA.Text & "$" & txtDWT.Text & "$" & txtDraft.Text & "$" & txtGRT.Text & "$" & txtVesselOUT.Text & "$" & NameAgent & "$Draft" & "$" & ProductName & "$" & ProductAmount & "$" & ProductAmountByProduct & "$" & nation & "$" & raioType.SelectedValue & "$" & ViewState("Status")
        End If
        If (radioPort.SelectedValue = "B") Then
            If Not (ViewState("OwnerColumn") & "" = "") Then
                Dim dsBulk As DataSet = Session("MAT_USE")
                Dim dsNewBulk As New DataSet
                Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
                Dim Count As Integer = 0
                For i As Integer = 0 To Owner.Length - 1
                    Dim _Owner As String = Owner(i).Split("฿")(0)
                    If (Owner(i).Split("฿")(1) <> "") Then
                        'ทำการแยก DataTable ของลูกค้าแต่ละคนออกจากกันเลย
                        Dim dtN As DataTable = dsBulk.Tables(0).Clone
                        If (dtN.Columns.Count < 10) Then
                            dtN.Columns.Add("Owner", GetType(String))
                            dtN.AcceptChanges()
                        End If
                        For j As Integer = 0 To gridTariff.Rows.Count - 1
                            Dim chk As CheckBox = CType(gridTariff.Rows(j).FindControl("chkOwner" & Count + 1), CheckBox)
                            If (chk.Checked) Then
                                Dim dr As DataRow = dtN.NewRow
                                dr.Item("MATERIAL") = gridTariff.DataKeys(j).Values("MATERIAL") & ""
                                dr.Item("Text_line") = gridTariff.DataKeys(j).Values("Text_line") & ""
                                dr.Item("Unit") = gridTariff.DataKeys(j).Values("Unit") & ""
                                dr.Item("Count") = gridTariff.DataKeys(j).Values("Count") & ""
                                dr.Item("MAT_Default") = gridTariff.DataKeys(j).Values("MAT_Default") & ""
                                dr.Item("KBETR") = gridTariff.DataKeys(j).Values("KBETR") & ""
                                dr.Item("KONWA") = gridTariff.DataKeys(j).Values("KONWA") & ""
                                dr.Item("MAT_Relation") = gridTariff.DataKeys(j).Values("Mat_Relation") & ""
                                dr.Item("MAT_ComputeM") = gridTariff.DataKeys(j).Values("MAT_ComputeM") & ""
                                dr.Item("Owner") = _Owner
                                dtN.Rows.Add(dr)
                                dtN.AcceptChanges()
                            End If
                        Next
                        Count += 1
                        dtN.TableName = "Bulk" & Count
                        dsNewBulk.Tables.Add(dtN.Copy)
                    End If
                Next
                Session("MAT_USE") = dsNewBulk
            End If

        End If


        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        Dim Vehicle As String = ""
        Dim Vehicle_Name As String = ""
        Dim LOA As String = ""
        Dim DWT As String = ""
        Dim Draft As String = ""
        Dim GRT As String = ""
        Dim OwnerRequest As String = ""
        Dim CNTRY As String = ""
        Dim Vehicle_TypeBuy As String = ""
        Dim BunkerFO_chk As String = ""
        Dim BunkerDO_chk As String = ""
        Dim BunkerFO_Point As String = ""
        Dim BunkerDO_Point As String = ""

        Dim Product_Name As String = ViewState("Product_NameAmount").ToString().Split("$")(0)
        If (chkFO.Checked) Then
            BunkerFO_chk = "Y"
            BunkerFO_Point = txtFO.Text.Trim()
            If (Product_Name.Trim <> "") Then
                Product_Name &= ",BunkerFO " & BunkerFO_Point & " คัน"
            Else
                Product_Name &= "BunkerFO " & BunkerFO_Point & " คัน"
            End If
        Else
            BunkerFO_chk = "N"
            BunkerFO_Point = "0"
        End If

        If (lbFT1.Text = "FT") Then
            If (txtLOA.Text.Trim() <> "") Then
                Try
                    txtLOA.Text = (CDbl(txtLOA.Text) * 3.281).ToString("############0.00")
                Catch ex As Exception

                End Try
            End If
            If (txtDraft.Text.Trim() <> "") Then
                Try
                    txtDraft.Text = (CDbl(txtDraft.Text) * 3.281).ToString("############0.00")
                Catch ex As Exception

                End Try
            End If
        End If

        If (chkDO.Checked) Then
            BunkerDO_chk = "Y"
            BunkerDO_Point = txtDO.Text.Trim()
            If (Product_Name.Trim <> "") Then
                Product_Name &= ",BunkerDO " & BunkerDO_Point & " คัน"
            Else
                Product_Name &= "BunkerDO " & BunkerDO_Point & " คัน"
            End If
        Else
            BunkerDO_chk = "N"
            BunkerDO_Point = "0"
        End If

        Dim File_Upload As String = ""
        Dim dt As DataTable = Session("Q88")
        For Each dr As DataRow In dt.Rows
            'File_Upload = File_Upload.Replace("," & dr.Item("File_Type"), "")
            'File_Upload &= "," & dr.Item("File_Type")
            File_Upload &= "," & dr.Item("File_name")
        Next
        If (File_Upload.Length > 0) Then
            File_Upload = File_Upload.Substring(1, File_Upload.Length - 1)
        End If

        Dim MAgent_no As String = ""
        Dim MAgent_name As String = ""
        Dim SAgent_name As String = ""
        Dim SAgent_no As String = ""
        If (txtid.Text.Trim = "") Then
            MAgent_no = ""
            MAgent_name = ""
        Else
            MAgent_no = txtid.Text.Split("-")(0)
            ' MAgent_name = txtid.Text.Split("-")(1)
            Dim AgentLoops() As String = txtid.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    MAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
        End If
        If (txtAgent.Text.Trim = "") Then
            SAgent_no = ""
            SAgent_name = ""
        Else
            SAgent_no = txtAgent.Text.Split("-")(0)
            'SAgent_name = txtAgent.Text.Split("-")(1)
            Dim AgentLoops() As String = txtAgent.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    SAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            SAgent_name = SAgent_name.Substring(1, SAgent_name.Length - 1)
        End If
        If (raioType.SelectedValue = "O") Then
            Vehicle_TypeBuy = radioTypeBuy.SelectedValue
        End If
        If (Session("Role") & "" = "00002") Then
            OwnerRequest = ""
        Else
            OwnerRequest = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        End If
        Dim standardTime As String = ""
        If (Session("Lay_Time") & "" = "") Then
            standardTime = "0"
        Else
            standardTime = Session("Lay_Time") & ""
        End If
        If (radioVehicle.SelectedValue = "0") Then
            Vehicle = txtVessel.Text.Split("-")(0)
            '  Vehicle_Name = txtVessel.Text.Split("-")(1)
            Dim AgentLoops() As String = txtVessel.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    Vehicle_Name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            Vehicle_Name = Vehicle_Name.Substring(1, Vehicle_Name.Length - 1)
            LOA = lbLOASHOW.Text.Trim()
            DWT = lbDWTSHow.Text.Trim()
            Draft = lbDraft.Text.Trim()
            GRT = lbGRTSHow.Text.Trim()
            CNTRY = lbNation.Text.Trim()
        Else
            Vehicle = "999999999"
            Vehicle_Name = txtVesselOUT.Text.Trim()
            LOA = txtLOA.Text.Trim()
            DWT = txtDWT.Text.Trim()
            Draft = txtDraft.Text.Trim()
            GRT = txtGRT.Text.Trim()
            CNTRY = ddlNation.SelectedValue.Replace("T", "TH")
        End If
        Dim shifting As String = ""
        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.InsertBooking(ViewState("EditBooking"), Booking, CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, "NB", "", "", "", "", "", Product_Name, ViewState("Product_NameAmount").ToString().Split("$")(1), MAgent_no, MAgent_name, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, ViewState("Product_NameAmount").ToString().Split("$")(3), ViewState("Product_NameAmount").ToString().Split("$")(4), ViewState("Product_NameAmount").ToString().Split("$")(2), File_Upload, CNTRY, txtLayTime.Text.Trim(), "N", "N", "N", BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, txtWater.Text.Trim(), "", standardTime, "", txtDemurrage.Text, ddlDemurrage.SelectedValue, txtElectricity.Text, shifting, conn, tran) > 0) Then
                If (clsFc.InsertBooking_Log(Booking_Log, Booking, CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, "NB", "", "", "", "", "", Product_Name, ViewState("Product_NameAmount").ToString().Split("$")(1), MAgent_no, MAgent_name, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, ViewState("Product_NameAmount").ToString().Split("$")(3), ViewState("Product_NameAmount").ToString().Split("$")(4), ViewState("Product_NameAmount").ToString().Split("$")(2), File_Upload, CNTRY, txtLayTime.Text, "N", "N", "N", BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, txtWater.Text.Trim(), "", "", "", "", "", "", "", "", standardTime, "", "N", txtDemurrage.Text, ddlDemurrage.SelectedValue, txtElectricity.Text, shifting, conn, tran) > 0) Then
                    Dim dsMat As DataSet = Session("MAT_USE")
                    If (clsFc.UpdatePREBookingStatusOneField(Booking, "Y", conn, tran) < 1) Then
                        condition = False
                    End If
                    clsFc.DeleteBookingTariff(Booking, "", conn, tran)
                    If (radioPort.SelectedValue = "L") Then
                        For Each dr As DataRow In dsMat.Tables(0).Rows
                            If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", Session("SumTotal") & "", conn, tran) > 0) Then
                                If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", conn, tran) < 1) Then
                                    condition = False
                                    Exit For
                                End If
                            Else
                                condition = False
                                Exit For
                            End If
                        Next
                    Else
                        For Each dtMat As DataTable In dsMat.Tables
                            Try
                                For Each dr As DataRow In dtMat.Rows
                                    If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", dr.Item("Owner"), Session("SumTotal") & "", conn, tran) > 0) Then
                                        If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", dr.Item("Owner"), conn, tran) < 1) Then
                                            condition = False
                                            Exit For
                                        End If
                                    Else
                                        condition = False
                                        Exit For
                                    End If
                                Next
                            Catch ex As Exception
                                For Each dr As DataRow In dsMat.Tables(0).Rows
                                    If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", Session("SumTotal") & "", conn, tran) > 0) Then
                                        If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", conn, tran) < 1) Then
                                            condition = False
                                            Exit For
                                        End If
                                    Else
                                        condition = False
                                        Exit For
                                    End If
                                Next
                            End Try

                        Next
                    End If

                    dsProduct = Session("Product_popup")
                    clsFc.DeleteBookingProduct(Booking, conn, tran)
                    For Each dr As DataRow In dsProduct.Rows
                        If (dr.Item("Product_no") & "" <> "") Then
                            Dim Destination As String = ""
                            If (dr.Item("Product_Event") = "L") Or (dr.Item("Product_Event") = "R") Then
                                Destination = dr.Item("LoadDestination")
                            Else
                                Destination = dr.Item("DischDestination")
                            End If
                            If (clsFc.InsertBooking_Product("", Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                                condition = False
                                Exit For
                            End If
                        End If

                    Next

                    clsFc.DeleteBooking_Upload(Booking, conn, tran)
                    For Each dr As DataRow In dt.Rows
                        If (clsFc.InsertBooking_Upload(Booking, dr.Item("File_nameGuid"), dr.Item("File_name"), dr.Item("File_type"), dr.Item("File_ContentType"), dr.Item("Upload_Type"), dr.Item("Description"), conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next

                Else
                    condition = False
                End If
            Else
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                ViewState("EditBooking") = ""
                Session("Product_popup") = CreateDatasetProduct()
                Session("Lay_Time") = "0"
                ViewState("PreBooking") = ""
                Session("MAT_USE") = ""
                Session("Value") = Nothing
                Session("Q88") = CreateFileDataTable()
                Session("StandardTimePlus") = 0
                ViewState("Status") = ""
                ViewState("EditBooking") = ""
                Session("Operation") = Nothing
                LoadDataMyBooking("", "", "", "")
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ !!');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & ex.Message & "');", True)
            txtRemark.Text = ex.Message
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก  !!');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Public Function CreateFileDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("File_nameGuid", GetType(String))
        dt.Columns.Add("File_name", GetType(String))
        dt.Columns.Add("File_Type", GetType(String))
        dt.Columns.Add("File_ContentType", GetType(String))
        dt.Columns.Add("Upload_Type", GetType(String))
        dt.Columns.Add("Description", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If (txtDate.Text.Trim = "") Or (txtDateTo.Text.Trim = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Lay Can/Lay Day!!');", True)
            Exit Sub
        End If

        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim Vehicle As String = ""
        Dim Vehicle_Name As String = ""
        Dim LOA As String = ""
        Dim DWT As String = ""
        Dim Draft As String = ""
        Dim GRT As String = ""
        Dim CNTRY As String = ""
        Dim Booking As String = ""

        Dim BunkerFO_chk As String = ""
        Dim BunkerDO_chk As String = ""
        Dim BunkerFO_Point As String = ""
        Dim BunkerDO_Point As String = ""

        If (chkFO.Checked) Then
            BunkerFO_chk = "Y"
            BunkerFO_Point = txtFO.Text.Trim()
        Else
            BunkerFO_chk = "N"
            BunkerFO_Point = "0"
        End If
        If (chkDO.Checked) Then
            BunkerDO_chk = "Y"
            BunkerDO_Point = txtDO.Text.Trim()
        Else
            BunkerDO_chk = "N"
            BunkerDO_Point = "0"
        End If
        Dim Vehicle_TypeBuy As String = ""
        ViewState("EditBooking") = "Edit"

        Booking = ViewState("PreBooking")
        If (radioVehicle.SelectedValue = "0") Then
            Vehicle = txtVessel.Text.Split("-")(0)
            '  Vehicle_Name = txtVessel.Text.Split("-")(1)
            Dim AgentLoops() As String = txtVessel.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    Vehicle_Name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            Vehicle_Name = Vehicle_Name.Substring(1, Vehicle_Name.Length - 1)
            LOA = lbLOASHOW.Text.Trim()
            DWT = lbDWTSHow.Text.Trim()
            Draft = lbDraft.Text.Trim()
            GRT = lbGRTSHow.Text.Trim()
            CNTRY = lbNation.Text.Trim()
        Else
            Vehicle = "999999999"
            Vehicle_Name = txtVesselOUT.Text.Trim()
            LOA = txtLOA.Text.Trim()
            DWT = txtDWT.Text.Trim()
            Draft = txtDraft.Text.Trim()
            GRT = txtGRT.Text.Trim()
            CNTRY = ddlNation.SelectedValue.Replace("T", "TH")
        End If
        If (raioType.SelectedValue = "O") Then
            Vehicle_TypeBuy = radioTypeBuy.SelectedValue
        End If
        Dim MAgent_no As String = ""
        Dim MAgent_name As String = ""
        Dim SAgent_name As String = ""
        Dim SAgent_no As String = ""
        If (txtid.Text.Trim = "") Then
            MAgent_no = ""
            MAgent_name = ""
        Else
            MAgent_no = txtid.Text.Split("-")(0)
            ' MAgent_name = txtid.Text.Split("-")(1)
            Dim AgentLoops() As String = txtid.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    MAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
        End If
        If (txtAgent.Text.Trim = "") Then
            SAgent_no = ""
            SAgent_name = ""
        Else
            SAgent_no = txtAgent.Text.Split("-")(0)
            'SAgent_name = txtAgent.Text.Split("-")(1)
            Dim AgentLoops() As String = txtAgent.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    SAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            SAgent_name = SAgent_name.Substring(1, SAgent_name.Length - 1)
        End If
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.InsertPre_Booking(ViewState("EditBooking"), Booking, CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, "N", MAgent_no, MAgent_name, CNTRY, txtWater.Text.Trim(), txtElectricity.Text, BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, txtLayTime.Text.Trim(), txtDemurrage.Text, ddlDemurrage.SelectedValue, conn, tran) > 0) Then
                Dim dsProduct As DataTable = Session("Product_popup")
                clsFc.DeleteBookingProduct(Booking, conn, tran)
                For Each dr As DataRow In dsProduct.Rows
                    If (dr.Item("Product_no") & "" <> "") Then
                        Dim Destination As String = ""
                        If (dr.Item("Product_Event") = "L") Or (dr.Item("Product_Event") = "R") Then
                            Destination = dr.Item("LoadDestination")
                        Else
                            Destination = dr.Item("DischDestination")
                        End If
                        If (clsFc.InsertBooking_Product("", Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    End If

                Next
            Else
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                ViewState("EditBooking") = ""
                Session("Product_popup") = CreateDatasetProduct()
                LoadDataMyBooking("", "", "", "")
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ !!');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            txtRemark.Text = ex.Message
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก  !!');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Sub btnSerachMyBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSerachMyBooking.Click
        Dim dateFrom As String = ""
        Dim dateTo As String = ""
        If (txtDateSearch.Text <> "") Then
            dateFrom = txtDateSearch.Text.Split(" ")(2) & CDate(txtDateSearch.Text).ToString("MMdd")
        End If
        Dim date_to As String = ""
        If (txtDateToSearch.Text <> "") Then
            dateTo = txtDateToSearch.Text.Split(" ")(2) & CDate(txtDateToSearch.Text).ToString("MMdd")
        End If
        LoadDataMyBooking(txtBooking_no.Text, txtVesselName.Text, dateFrom, dateTo)
    End Sub

    Private Sub imgSendMail_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgSendMail.Click
        Dim test As String = clsFc.sendmail(clsGet.Get_EmailForSendAgent(ViewState("Booking")), "", "iPORT", GenBodyMailBooking(), "")
        If (test = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ส่ง E-Mail สำเร็จ !!');", True)
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & test & " !!');", True)
        End If
    End Sub

    Private Function GenBodyMailEstimate() As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='center'><font class='White-Style' font-weight:bold style='color:#000000'>Estimate File !!</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        Return HTML
    End Function

    Private Function GenBodyMailBooking() As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & lbBooking.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Sold To :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & lbSoldTo.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Vessel :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & lbVessel.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Lay Can\Lay Day :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & lbLaycan.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"

        HTML &= "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Product :</font>&nbsp;</td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Operation</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Product Group</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Product</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Amount</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Unit</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Buyer</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Seller</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Destination</font></td>"
        HTML &= "<td align='left' style='background-color:#2c9c1c;'><font class='White-Style' style='color:#ffffff'>Detail</font></td>"
        HTML &= "</tr>"

        For i As Integer = 0 To gridProduct.Rows.Count - 1
            HTML &= "<tr>"
            HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'></font>&nbsp;</td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(0).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(1).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(2).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(3).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(4).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(5).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(6).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(7).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "<td align='left' style='background-color:#c0e9ad;'><font class='White-Style' style='color:#000000'>" & gridProduct.Rows(i).Cells(8).Text.Replace("&nbsp;", "") & "" & "</font></td>"
            HTML &= "</tr>"
        Next

        HTML &= "</table>"
        Return HTML
    End Function

    Private Sub btnSendMailActual_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSendMailActual.Click
        Dim test As String = clsFc.sendmail(clsGet.Get_EmailForSendAgent(ViewState("Booking")), "", "", GenBodyMailEstimate(), GetPath())
        'Dim test As String = clsFc.sendmail("kunsky_065@hotmail.com", "", "", GenBodyMailEstimate(), GetPath())
        If (test = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ส่ง E-Mail สำเร็จ !!');", True)
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & test & " !!');", True)
        End If
        'Dim test As String = clsFc.sendmail("", "ongarj@wisethailand.com", "", "Mail From iPORT", GenBodyMailEstimate(), Server.MapPath("..") & "/WriteReport/5e47003a-3e79-4db9-827e-5a9eedacf9b9.pdf")
        'ใช้ spilt("xxx and xxx"," and ") ตัดคำ
    End Sub

    Private Function GetPath() As String
        Dim path As String = CreateReport()
        If (path <> "") Then
            Dim str() As String = Split(path, "WriteReport")
            path = Server.MapPath("..") & "/WriteReport" & str(str.Length - 1)
        End If
        Return path
    End Function

    Private Function CreateReport() As String
        Dim service As New _ReportingService.Report

        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        Dim Orientation As Boolean = True
        Dim ReportName As String = String.Empty
        Dim reportDataSource As String = String.Empty
        Dim paraName As String = String.Empty
        Dim paraValue As String = String.Empty
        Dim reportType As String = String.Empty
        Dim urlDisplay As String = String.Empty
        Dim dsReport As New DataSet

        Dim Vat As String = ""
        Dim dsConfig As DataSet = Session("Config")
        If (dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(1) = "00") Then
            Vat = CInt(dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(0)).ToString()
        Else
            Vat = dsConfig.Tables(0).Rows(0).Item("Vat").ToString()
        End If


        Dim dt As DataTable = CreateDataTableForReport()
        Dim dSITem As DataTable = ViewState("DSItem")
        For Each dr As DataRow In dSITem.Rows
            Dim dn As DataRow = dt.NewRow
            dn.Item("MATERIAL") = dr.Item("id")
            dn.Item("Text_line") = dr.Item("MAT_NAME")
            dn.Item("data1") = dr.Item("data1")
            dn.Item("data2") = dr.Item("data2")
            dn.Item("data3") = dr.Item("data3")
            dn.Item("data4") = dr.Item("data4")
            dt.Rows.Add(dn)
            dt.AcceptChanges()
        Next
        If dt.Rows.Count > 0 Then

            dt.Columns.Add("VAT", GetType(String))
            dt.Columns.Add("VAT_AMOUNT", GetType(String))
            dt.Columns.Add("NET", GetType(String))
            dt.Columns.Add("AMOUNT", GetType(String))
            dt.Columns.Add("Text_AMOUNT", GetType(String))
            dt.AcceptChanges()
            Dim NET As Double = 0.0
            For i As Integer = 0 To dt.Rows.Count - 1
                NET = NET + CDbl(CDbl(dt.Rows(i).Item("data4")).ToString("##############0.00"))
            Next
            Dim VAT_AMOUNT As String = ((NET * CDbl(Vat)) / 100).ToString("############.00")
            Dim AMOUNT As String = NET + CDbl(((NET * CDbl(Vat)) / 100).ToString("############.00"))
            Dim Text_AMOUNT As String = ConvertMoneyToText((NET + CDbl(((NET * CDbl(Vat)) / 100).ToString("############.00"))).ToString())
            For i As Integer = 0 To dt.Rows.Count - 1
                Dim MAT As String = ""
                Try
                    MAT = CInt(dt.Rows(i).Item("MATERIAL"))
                Catch ex As Exception
                    MAT = dt.Rows(i).Item("MATERIAL")
                End Try
                dt.Rows(i).Item("MATERIAL") = MAT
                dt.Rows(i).Item("VAT") = Vat
                dt.Rows(i).Item("VAT_AMOUNT") = FormatNumber(VAT_AMOUNT, 2)
                dt.Rows(i).Item("NET") = FormatNumber(NET, 2)
                dt.Rows(i).Item("AMOUNT") = FormatNumber(AMOUNT, 2)
                dt.Rows(i).Item("Text_AMOUNT") = Text_AMOUNT
                Try
                    dt.Rows(i).Item("data1") = FormatNumber(dt.Rows(i).Item("data1"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data2") = FormatNumber(dt.Rows(i).Item("data2"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data3") = FormatNumber(dt.Rows(i).Item("data3"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data4") = FormatNumber(dt.Rows(i).Item("data4"), 2)
                Catch ex As Exception

                End Try
                dt.AcceptChanges()
            Next
            dsReport.Tables.Add(dt.Copy)
            dsReport.AcceptChanges()
            ReportName = "Actual_Report.rdlc"
            ' dsReport = New DataSet
            reportDataSource = "Actual_Report_Actual"

            dt = clsGet.Get_BookingOneRecord(ViewState("Booking")).Tables(0)


            paraName = "SHIP;PERIOD;LAYTIME;AGENT;LOA;GRT;DWT;PO;WHARF;Booking_no;Estimate"
            If (dt.Rows.Count > 0) Then
                Dim PORT As String = dt.Rows(0).Item("PORT")
                Dim LAYTIME As String = dt.Rows(0).Item("Lay_Time")
                Dim MAGEnt_Name As String = ""
                Dim Name() As String = lbAgent.Text.Split(":")(1).Split("-")
                For i As Integer = 1 To Name.Length - 1
                    MAGEnt_Name &= Name(i) & " "
                Next

                dt = clsGet.Get_BookingWharf(ViewState("Booking"))
                Dim WHARF As String = dt.Rows(0).Item("Wharf")
                Dim PERIOD As String = ""
                PERIOD &= ""
                Dim PO As String = ""
                Try
                    PO = FormatNumber(ViewState("PO"), 2)
                Catch ex As Exception
                    PO = "0"
                End Try
                paraValue = lbShip.Text.Split(":")(1) & ";" & PERIOD & ";" & LAYTIME & ";" & MAGEnt_Name & ";" & lbLoA.Text.Split(":")(1) & ";" & lbGrt.Text.Split(":")(1) & ";" & lbdWT.Text.Split(":")(1) & ";" & lbPo.Text.Split(":")(1).Replace("MT", "") & " MT" & ";" & WHARF & ";" & ViewState("Booking") & ";ESTIMATE"
            Else
                paraValue = ";;;;;;;;;"
            End If

            Orientation = True
            reportType = "pdf"

            Try
                urlDisplay = service.CreateReporting(dsReport, reportDataSource, reportType, ReportName, paraName, paraValue, Orientation, "")

                Return urlDisplay
            Catch ex As Exception
                Dim errortxt As String = ex.Message
                Return ""
            End Try
        Else
            Return ""
        End If
    End Function

    Private Function CreateDataTableForReport()
        Dim dt As New DataTable
        dt.Columns.Add("MATERIAL", GetType(String))
        dt.Columns.Add("Text_line", GetType(String))
        dt.Columns.Add("data1", GetType(String))
        dt.Columns.Add("data2", GetType(String))
        dt.Columns.Add("data3", GetType(String))
        dt.Columns.Add("data4", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Function ConvertMoneyToText(ByVal Money As String) As String
        Dim Digit As String = Money.Split(".")(0)
        Dim SubMoney As String
        Try
            SubMoney = Money.Split(".")(1)
        Catch ex As Exception
            SubMoney = "00"
        End Try
        Dim COuntLength As Int16 = Digit.Length

        Dim TxtMoney As String = ""

        For i As Integer = 0 To COuntLength - 1
            If (COuntLength > 7) Then
                Select Case (Digit.Substring(0, 1).ToString())
                    Case "9" : TxtMoney &= "เก้า"
                    Case "8" : TxtMoney &= "แปด"
                    Case "7" : TxtMoney &= "เจ็ด"
                    Case "6" : TxtMoney &= "หก"
                    Case "5" : TxtMoney &= "ห้า"
                    Case "4" : TxtMoney &= "สี่"
                    Case "3" : TxtMoney &= "สาม"
                    Case "2" : TxtMoney &= "สอง"
                    Case "1" : TxtMoney &= "หนึ่ง"
                End Select

                Select Case (COuntLength.ToString)
                    Case "13" : TxtMoney &= "ล้านล้าน"
                    Case "12" : TxtMoney &= "แสนล้าน"
                    Case "11" : TxtMoney &= "หมื่นล้าน"
                    Case "10" : TxtMoney &= "พันล้าน"
                    Case "9" : TxtMoney &= "ร้อยล้าน"
                    Case "8" : TxtMoney &= "สิบล้าน"
                End Select
            Else
                Select Case (Digit.Substring(0, 1).ToString())
                    Case "9" : TxtMoney &= "เก้า"
                    Case "8" : TxtMoney &= "แปด"
                    Case "7" : TxtMoney &= "เจ็ด"
                    Case "6" : TxtMoney &= "หก"
                    Case "5" : TxtMoney &= "ห้า"
                    Case "4" : TxtMoney &= "สี่"
                    Case "3" : TxtMoney &= "สาม"
                    Case "2"
                        If (COuntLength.ToString() = "2") Then
                            TxtMoney &= "ยี่"
                        Else
                            TxtMoney &= "สอง"
                        End If

                    Case "1"
                        If (COuntLength.ToString() = "2") Then
                            TxtMoney &= "เอ็ด"
                        Else
                            TxtMoney &= "หนึ่ง"
                        End If
                End Select

                Select Case (COuntLength.ToString)
                    Case "7" : TxtMoney &= "ล้าน"
                    Case "6" : TxtMoney &= "แสน"
                    Case "5" : TxtMoney &= "หมื่น"
                    Case "4" : TxtMoney &= "พัน"
                    Case "3" : TxtMoney &= "ร้อย"
                    Case "2" : TxtMoney &= "สิบ"
                    Case "1" : TxtMoney &= "บาท"
                End Select
            End If
            Select Case (COuntLength.ToString())
                Case "13"
                    Digit = CInt(Digit) Mod 1000000000000
                Case "12"
                    Digit = CInt(Digit) Mod 100000000000
                Case "11"
                    Digit = CInt(Digit) Mod 10000000000
                Case "10"
                    Digit = CInt(Digit) Mod 1000000000
                Case "9"
                    Digit = CInt(Digit) Mod 100000000
                Case "8"
                    Digit = CInt(Digit) Mod 10000000
                Case "7"
                    Digit = CInt(Digit) Mod 1000000
                Case "6"
                    Digit = CInt(Digit) Mod 100000
                Case "5"
                    Digit = CInt(Digit) Mod 10000
                Case "4"
                    Digit = CInt(Digit) Mod 1000
                Case "3"
                    Digit = CInt(Digit) Mod 100
                Case "2"
                    Digit = CInt(Digit) Mod 10
                Case "1"
                    Digit = CInt(Digit) Mod 1
            End Select
            COuntLength -= 1
        Next
        If (SubMoney <> "00") Then
            If (SubMoney.Length = 2) Then
                Select Case (SubMoney.Substring(0, 1))
                    Case "9" : TxtMoney &= "เก้าสิบ"
                    Case "8" : TxtMoney &= "แปดสิบ"
                    Case "7" : TxtMoney &= "เจ็ดสิบ"
                    Case "6" : TxtMoney &= "หกสิบ"
                    Case "5" : TxtMoney &= "ห้าสิบ"
                    Case "4" : TxtMoney &= "สี่สิบ"
                    Case "3" : TxtMoney &= "สามสิบ"
                    Case "2" : TxtMoney &= "ยี่สิบ"
                    Case "1" : TxtMoney &= "สิบ"
                End Select
                Select Case (SubMoney.Substring(1, 1))
                    Case "9" : TxtMoney &= "เก้าสตางค์"
                    Case "8" : TxtMoney &= "แปดสตางค์"
                    Case "7" : TxtMoney &= "เจ็ดสตางค์"
                    Case "6" : TxtMoney &= "หกสตางค์"
                    Case "5" : TxtMoney &= "ห้าสตางค์"
                    Case "4" : TxtMoney &= "สี่สตางค์"
                    Case "3" : TxtMoney &= "สามสตางค์"
                    Case "2" : TxtMoney &= "สองสตางค์"
                    Case "1"
                        If (SubMoney.Length = 2) Then
                            If (SubMoney.Substring(0, 1) = "0") Then
                                TxtMoney &= "หนึ่งสตางค์"
                            Else
                                TxtMoney &= "เอ็ดสตางค์"
                            End If

                        Else
                            TxtMoney &= "หนึ่งสตางค์"
                        End If
                End Select
            Else
                Select Case (SubMoney.Substring(0, 1))
                    Case "9" : TxtMoney &= "เก้าสิบสตางค์"
                    Case "8" : TxtMoney &= "แปดสิบสตางค์"
                    Case "7" : TxtMoney &= "เจ็ดสิบสตางค์"
                    Case "6" : TxtMoney &= "หกสิบสตางค์"
                    Case "5" : TxtMoney &= "ห้าสิบสตางค์"
                    Case "4" : TxtMoney &= "สี่สิบสตางค์"
                    Case "3" : TxtMoney &= "สามสิบสตางค์"
                    Case "2" : TxtMoney &= "ยี่สิบสตางค์"
                    Case "1" : TxtMoney &= "สิบสตางค์"
                End Select
            End If
        End If
        Return TxtMoney
    End Function

    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnPrint.Click
        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "window.open('" + CreateReport() + "','_blank','" + optWindow + "');", True)
    End Sub
End Class